package com.jt.www.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.jt.www.common.service.CommonService;
import com.jt.www.domain.dto.JtBranch;
import com.jt.www.domain.dto.UserBranchAndProvCode;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.remote.UserClient;
import com.jt.www.util.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by shaoyn on 2020/02/16.
 */
@Service
public class CommonServiceImpl implements CommonService {

    public static final Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);
    private static final String SYS_CODE = "sys_edu_man";
    @Autowired
    private UserClient userClient;

    /**
     * 得到下一个整点
     * @return
     */
    public String nextHourTime(){
        long oneHour = 60 * 60 * 1000;
        long time = System.currentTimeMillis();
        long newTime = time / (oneHour) * oneHour + oneHour;
        String nextHourTime =  DateUtils.format(new Date(newTime), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        return nextHourTime;
    }

    @Override
    public ResponseEntity<GenericDataResponse<UserBranchAndProvCode>> getBranchList(String findCode, String userCode, String branchName) {

        List<JtBranch> retList = Lists.newArrayList();
        String provCode = "";
        try {
            GenericListResponse<JtBranch> response = userClient.getJtBranchByChannel("edu");
            log.info("{} 查询用户中心机构列表出参:{}", findCode, JSON.toJSONString(response));
            if(GenericListResponse.CODE_OK.equals(response.getCode()) && CollectionUtils.isNotEmpty(response.getList())){
                //添加 广东营业部
                JtBranch jtBranch = new JtBranch();
                jtBranch.setJtBranchName("广东营业部");
                jtBranch.setCode("JT0170001");
                List<JtBranch> userBranchList = response.getList();
                userBranchList.add(jtBranch);
                //得到登录用户的分支机构
                //请求用户中心
                ResponseEntity<GenericDataResponse<Map<String, Object>>> responseEntity = userClient.queryUserRoleAndAuthority(userCode, SYS_CODE);
                log.debug("{} 查询用户分支机构及地区权限 用户中心返回值 jtBranchs = {}", findCode, JSON.toJSONString(responseEntity));
                LinkedHashMap<String, String> dataPopedom = (LinkedHashMap) responseEntity.getBody().getData().get("dataPopedom");
                // 获取区域码, 可能是城市码,省编码,  多个值是以逗号隔开
                String dataArea = dataPopedom.get("dataArea");
                //如果只配置了一个地区，则返回该地区所对应的省，其他不返回。
                if (StringUtils.isNotBlank(dataArea) && dataArea.length() == 6
                        && !dataArea.startsWith("00")) {
                    provCode = dataArea.substring(0, 2) + "0000";
                }
                String jtBranchs = dataPopedom.get("jtBranchs");

                for(JtBranch jtBranch1 : userBranchList){
                    //模糊查询
                    if(StringUtils.isBlank(branchName)
                            || jtBranch1.getJtBranchName().contains(branchName)){
                        //如果是当前用户的分支机构放到第一位
                        if(jtBranchs.contains(jtBranch1.getCode())){
                            retList.add(0, jtBranch1);
                        } else {
                            retList.add(jtBranch1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{} 查询用户分支机构及地区权限异常", findCode,  e);
        }

        UserBranchAndProvCode userBranchAndProvCode = new UserBranchAndProvCode();
        userBranchAndProvCode.setProvCode(provCode);
        if(CollectionUtils.isNotEmpty(retList)){
            userBranchAndProvCode.setJtBranches(retList);
        }
        return GenericDataResponse.okWithData(userBranchAndProvCode);
    }

}
